function Snake(el) {
    // 保存地图对象
    this.el = el
    // 存蛇
    this.len = 20
    this.snakeObj = [{
        x: 3,
        y: 2,
        color: 'green',
        el: null
    }, {
        x: 2,
        y: 2,
        color: 'red',
        el: null
    }, {
        x: 1,
        y: 2,
        color: 'red',
        el: null
    }]
    this.direction = 'right'
}
Snake.prototype.remove = function () {
    for (let i = 0; i < this.snakeObj.length; i++) {
        // 保存蛇节对象
        // this.snakeObj[i].ele
        if (this.snakeObj[i].el) { // 开始没有保存蛇节对象
            // 所以增加判断  当保存了 再移除
            this.el.removeChild(this.snakeObj[i].el)
        }
    }
}

Snake.prototype.create = function () {
    // 地图上清除蛇
    this.remove()
    // 循环遍历创建蛇
    for (let i = 0; i < this.snakeObj.length; i++) {
        // 1 创建蛇标签对象
        let divObj = document.createElement('div')
        // 2 设置宽 高 坐标 颜色 
        divObj.style.width = this.len + 'px'
        divObj.style.height = this.len + 'px'
        divObj.style.position = 'absolute'
        divObj.style.left = this.snakeObj[i].x * this.len + 'px'
        divObj.style.top = this.snakeObj[i].y * this.len + 'px'
        divObj.style.background = this.snakeObj[i].color
        this.snakeObj[i].el = divObj
        // 3 放在页面展示
        this.el.appendChild(divObj)
    }
}

Snake.prototype.move = function () {

    // for (let i = 0; i < this.snakeObj.length; i++) {
    //     this.snakeObj[i].x += 1
    // }
    for (let i = this.snakeObj.length - 1; i > 0; i--) {
        this.snakeObj[i].x = this.snakeObj[i - 1].x
        this.snakeObj[i].y = this.snakeObj[i - 1].y
    }
    switch (this.direction) {
        case 'top':
            this.snakeObj[0].y -= 1
            break;

        case 'bottom':
            this.snakeObj[0].y += 1
            break;

        case 'left':
            this.snakeObj[0].x -= 1
            break;
        case 'right':
            this.snakeObj[0].x += 1
            break;
    }
    // 然后重新创建
    this.create()
}